import { ref, computed } from "vue";
import { defineStore } from "pinia";
import { getToken, setToken, removeToken } from "@/utils/token";
import { getLogin, getUser } from "@/api";

export const useUserStore = defineStore(
  "user",
  {
    persist: true,
    state: () => ({
      token: getToken(),
      username: "",
      userId: "",
      email: ""
    }),
    actions: {
      //登录函数
      async login(loginFrom) {
        const ret = await getLogin(loginFrom);
        const newToken = ret.token;
        setToken(newToken);
        this.token = newToken;
      },
      async getLoginUser() {
        const ret = await getUser()
        this.username = ret.User.username
        this.userId = ret.User.userId
        this.email = ret.User.email
      },
      //退出函数
      logout() {
        removeToken();
        this.token = "";
        this.username = "";
        this.userId = "";
        this.email = "";
      },
    },
  }
);
